package cn.kgc.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/2/28
 * @description  springmvc中如何实现页面的转发和重定向操作
 */
@Controller
@RequestMapping("fr")
public class FRController {

    //  转发
    @RequestMapping("m1")
    public String  method1(){
        return "hello";
    }


    //  转发
    @RequestMapping("m2")
    public void   method2(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {

        req.setAttribute("info","hello HttpServletRequest");
        // 通过请求对象实现页面的转发
        req.getRequestDispatcher("/hello.jsp").forward(req,resp);
    }


    //  返回值类型是字符串类型  在字符串前添加forward:关键词标识本次的页面跳转使用转发的方式
    // 添加了forward:关键词之后的字符串 在实现转发时 不在经过视图解析器  /hello.jsp
    @RequestMapping("m3")
    public String method3(){
        return "forward:/hello.jsp";
    }


    /**
     *重定向实现页面跳转  hello.jsp
     */
    @RequestMapping("m4")
    public void   method4(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.setAttribute("info","hello HttpServletResponse");
        resp.sendRedirect("/hello.jsp");
    }

    //  mvc  重定向   redirect  不会经过视图解析器
    @RequestMapping("m5")
    public String  method5(HttpSession session){
        session.setAttribute("info","hello redirect");
        return "redirect:/hello.jsp";
    }
}


